<template>
    <a-modal
        width="60%"
        centered
        :visible="visible"
        :title="title"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <!-- 添加 -->
        <a-form
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 14 }"
            :model="addForm"
            v-if="type && type === 4"
            style="min-height: 550px"
        >
            <a-form-item label="是否全库批量导入：" required>
                <a-radio-group
                    name="radioGroup"
                    v-model:value="addForm.isMulti"
                >
                    <a-radio :value="0">单表导入</a-radio>
                    <!-- <a-radio :value="1">全库导入</a-radio>
                    <a-radio :value="2">Sql导入</a-radio> -->
                </a-radio-group>
            </a-form-item>
            <a-form-item
                label="数据源："
                required
                v-bind="validateInfos.sjyid"
                name="sjyid"
            >
                <a-select
                    v-model:value="addForm.sjyid"
                    :filter-option="filterOption"
                    show-search
                    @change="handleChange"
                >
                    <a-select-option v-for="d in sjy" :key="d.id">
                        数据源类型：【{{ d.sjylx }}】- 数据源名称：【{{
                            d.sjymc
                        }}】
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="用户/SCHEMA："
                required
                v-bind="validateInfos.ssyh"
                name="ssyh"
            >
                <a-select
                    v-model:value="addForm.ssyh"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in user" :key="d.id">
                        {{ d.text }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据对象类型："
                required
                v-bind="validateInfos.sjdxlx"
                name="sjdxlx"
            >
                <a-select
                    v-model:value="addForm.sjdxlx"
                    :filter-option="filterOption"
                    show-search
                    @change="handleChangeType"
                >
                    <a-select-option value=""
                        >请输入数据对象类型</a-select-option
                    >
                    <a-select-option value="01">表</a-select-option>
                    <a-select-option value="2">视图</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据表名："
                required
                v-if="addForm.isMulti === 0"
                v-bind="validateInfos.sjdxmc"
                name="sjdxmc"
            >
                <a-select
                    v-model:value="addForm.sjdxmc"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in tableNameList" :key="d.id">
                        {{ d.text }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据表中文名："
                required
                v-bind="validateInfos.sjdxms"
                v-if="addForm.isMulti === 0"
                name="sjdxms"
            >
                <a-input v-model:value="addForm.sjdxms"></a-input>
            </a-form-item>
            <a-form-item
                label="数据维度："
                required
                v-bind="validateInfos.ywlxid"
                v-if="addForm.isMulti === 0"
                name="ywlxid"
            >
                <a-select
                    v-model:value="addForm.ywlxid"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in ryxx" :key="d.dictValue">
                        {{ d.dictLabel }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="备注：" v-if="addForm.isMulti === 0" name="bz">
                <a-textarea
                    v-model:value="addForm.bz"
                    showCount
                    :maxlength="500"
                />
            </a-form-item>
            <!-- <a-form-item
                label="导入过滤（选填）："
                v-if="addForm.isMulti === 1"
            >
                <a-input
                    v-model:value="addForm.filter"
                    placeholder="请输入过滤条件，例如：sys_user lib* sm*"
                ></a-input>
                <p style="color: #afb0b1; font-size: 12px">
                    <ExclamationCircleOutlined />请输入要过滤的表或前缀以空格分隔，表前缀用*号结尾，如sys_user
                    lib* sm*
                </p>
            </a-form-item> -->
            <!-- <a-form-item label="数据表SQL语句：" v-if="addForm.isMulti === 2">
                <a-input
                    v-model:value="addForm.tablesql"
                    placeholder="请输入要导入的数据表SQL，示例：select id, tablename as sjdxmc, tablenamezw as sjdxms, ms as bz from test.zhb"
                ></a-input>
                <p style="color: #afb0b1; font-size: 12px; line-height: 1.4">
                    <ExclamationCircleOutlined /> SQL必须包含
                    id、sjdxmc、sjdxms、bz这四个字段，若没有请用如：'' as
                    bz代替。并且查询的时候需要制定schema名称，如：from
                    schema.表名，具体示例看上面水印.
                </p>
            </a-form-item>
            <a-form-item label="数据表SQL语句：" v-if="addForm.isMulti === 2">
                <a-input
                    v-model:value="addForm.zdsql"
                    placeholder="请输入要导入的字段信息SQL，示例：select id, zdmc, zdms, zdcd, zdlx, plxx, tableid, sfzj from test.zdzhb"
                ></a-input>
                <p style="color: #afb0b1; font-size: 12px; line-height: 1.4">
                    <ExclamationCircleOutlined />
                    SQL必须包含zdmc、zdms、zdcd、zdlx、plxx、tableid、sfzj这七个字段，若没有请用如：''
                    as plxx代替。并且查询的时候需要制定schema名称，如：from
                    schema.表名，具体示例看上面水印.
                </p>
            </a-form-item> -->
        </a-form>

        <!-- 数据预览 -->
        <a-table
            :pagination="false"
            :rowKey="(record) => record.customId"
            :columns="createColumns"
            :data-source="dataSource"
            size="small"
            v-if="type && type === 3"
            style="height: 550px; overflow-y: auto"
        >
        </a-table>

        <!-- 配置字段 -->
        <div v-if="type && type === 2">
            <a-table
                :pagination="false"
                :rowKey="(record, index) => (record.id ? record.id : index)"
                :columns="columns"
                :data-source="dataSource"
                style="height: 550px; overflow-y: auto"
            >
                <!-- <template #sfzj="{ record, index }">
                    <a-checkbox
                        :checked="record.sfzj === '1'"
                        @change="onCheckChange(record.sfzj, index)"
                    ></a-checkbox>
                </template> -->
                <template #sfkjzd="{ record, index }">
                    <a-checkbox
                        :checked="record.sfkjzd === '1'"
                        @change="
                            onCheckTypeChange(record.sfkjzd, index, 'sfkjzd')
                        "
                    ></a-checkbox>
                </template>
                <template #sfsjzd="{ record, index }">
                    <a-checkbox
                        :checked="record.sfsjzd === '1'"
                        @change="
                            onCheckTypeChange(record.sfsjzd, index, 'sfsjzd')
                        "
                    ></a-checkbox>
                </template>
                <template #operation="{ record, index }">
                    <a-popconfirm
                        title="你确定删除这条数据?"
                        ok-text="确认"
                        cancel-text="取消"
                        @confirm="onDel(record.id, index)"
                    >
                        <MinusCircleOutlined
                            :style="{ fontSize: '20px', color: '#13c2c2' }"
                        />
                    </a-popconfirm>
                </template>
            </a-table>
        </div>

        <!-- 编辑 -->
        <a-form
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 14 }"
            :model="form"
            v-if="type && type === 1"
        >
            <a-form-item
                label="数据表中文名："
                required
                v-bind="validateInfos.sjdxms"
            >
                <a-input v-model:value="form.sjdxms"></a-input>
            </a-form-item>
            <a-form-item label="数据源：" required v-bind="validateInfos.sjymc">
                <a-select
                    v-model:value="form.sjymc"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in sjy" :key="d.id">
                        {{ d.sjymc }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="用户/SCHEMA："
                required
                v-bind="validateInfos.ssyh"
            >
                <a-select
                    v-model:value="form.ssyh"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in user" :key="d.id">
                        {{ d.text }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据对象类型："
                required
                v-bind="validateInfos.sjdxlx"
            >
                <a-select
                    v-model:value="form.sjdxlx"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in sjdxlx" :key="d.value">
                        {{ d.text }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据表名："
                required
                v-bind="validateInfos.sjdxmc"
            >
                <a-select
                    v-model:value="form.sjdxmc"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in tableName" :key="d.id">
                        {{ d.text }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item
                label="数据维度："
                required
                v-bind="validateInfos.ywlxid"
            >
                <a-select
                    v-model:value="form.ywlxid"
                    :filter-option="filterOption"
                    show-search
                >
                    <a-select-option v-for="d in ryxx" :key="d.dictValue">
                        {{ d.dictLabel }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="备注：">
                <a-textarea
                    v-model:value="form.bz"
                    showCount
                    :maxlength="500"
                />
            </a-form-item>
        </a-form>
        <template #footer>
            <a-button key="back" @click="handleCancel">关闭</a-button>
            <a-button
                key="submit"
                type="primary"
                :loading="loading"
                @click="handleOk"
                >确认</a-button
            >
        </template>
    </a-modal>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import {
    MinusCircleOutlined,
    PlusOutlined,
    ReloadOutlined,
    SaveOutlined,
    InfoCircleFilled,
    ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { setFieldRemove, dataEdit } from "@/api/data-object";
import editForm from "./editForm";
import addForm from "./addForm";
import { useForm } from "@ant-design-vue/use";
import { message } from "ant-design-vue";
import { stringify } from "qs";
import { ryxx } from "@/filter/index";
export default defineComponent({
    name: "ModalO",
    emits: ["handleOk", "handleCancel"],
    components: {
        MinusCircleOutlined,
        PlusOutlined,
        ReloadOutlined,
        SaveOutlined,
        InfoCircleFilled,
        ExclamationCircleOutlined,
    },
    props: {
        loading: Boolean,
        visible: Boolean,
        title: String,
        row: {
            type: Object,
            default: {},
        },
        type: Number,
        userList: Array,
        tableNameList: Array,
        dataSource: Array,
        createColumns: Array,
        sjy: Array,
    },
    setup(props, { emit }) {
        const {
            row,
            userList,
            tableNameList,
            dataSource,
            type,
            sjy,
        }: any = toRefs(props);
        const { data, form, rulesRef } = editForm(row, userList, tableNameList);
        const { addStore, rulesRefAdd, rulesRefAdd_tow } = addForm(sjy);
        const state = reactive({
            dataSource,
            columns: [
                {
                    title: "字段名称",
                    dataIndex: "zdmc",
                    slots: { customRender: "zdmc" },
                },
                {
                    title: "字段描述",
                    dataIndex: "zdms",
                    slots: { customRender: "zdms" },
                },
                {
                    title: "字段类型",
                    dataIndex: "sjlx",
                    slots: { customRender: "sjlx" },
                },
                {
                    title: "字段长度",
                    dataIndex: "zdcd",
                    slots: { customRender: "zdcd" },
                },
                // {
                //     title: "是否主键",
                //     dataIndex: "sfzj",
                //     slots: { customRender: "sfzj" },
                // },
                {
                    title: "字段排序",
                    dataIndex: "plxx",
                    slots: { customRender: "plxx" },
                },
                {
                    title: "空间字段",
                    dataIndex: "sfkjzd",
                    slots: { customRender: "sfkjzd" },
                },
                {
                    title: "时间字段",
                    dataIndex: "sfsjzd",
                    slots: { customRender: "sfsjzd" },
                },
                {
                    title: "操作",
                    dataIndex: "operation",
                    slots: { customRender: "operation" },
                },
            ],
            validateInfos: {},
            resetFields: () => {},
            onCheckTypeChange: (sign: string, index: number, name: string) => {
                state.dataSource[index][name] = sign === "0" ? "1" : "0";
                dataEdit(state.dataSource[index]).then(({ msg }: any) => {
                    message.success(msg);
                });
            },
            onCheckChange: (sfzj: string, index: number) => {
                state.dataSource.forEach((e: any) => {
                    e.sfzj = "0";
                });
                state.dataSource[index].sfzj = !sfzj
                    ? "1"
                    : sfzj === "0"
                    ? "1"
                    : "0";
                dataEdit(state.dataSource[index]).then(({ msg }: any) => {
                    message.success(msg);
                });
            },
            onDel: (id: string, index: number) => {
                message.loading("正在删除...", 1).then(
                    () => {
                        setFieldRemove(id).then(({ msg }: any) => {
                            state.dataSource.splice(index, 1);
                            message.success(msg);
                        });
                    },
                    () => {}
                );
            },
            //数据处理
            dataHandle: (dataSource: any[]) => {
                let creatArr = [];
                const head = stringify({
                    sjjid: dataSource[0].sjjid,
                    sjdxmc: dataSource[0].sjdxmc,
                });
                creatArr.push(`${head}&`);
                for (let i = 0; i < dataSource.length; i++) {
                    const e = dataSource[i];
                    const createObject = {
                        zdms: e.zdms,
                        zdmc: e.zdmc,
                        sjlx: e.sjlx,
                        zdcd: e.zdcd,
                        plxx: e.plxx ? e.plxx : "",
                        sfkjzd: e.sfkjzd,
                        sfsjzd: e.sfsjzd,
                    };
                    let s = stringify(createObject);
                    creatArr.push(`${s}&`);
                }
                return creatArr;
            },
            //确认
            handleOk: () => {
                // type 1：编辑 2：配置字段 3：数据预览 4:添加数据
                switch (type.value) {
                    case 3:
                        emit("handleCancel");
                        break;
                    case 2:
                        let dataSource = state
                            .dataHandle(state.dataSource)
                            .join("");
                        let kjzd: string[] = [],
                            sjzd: string[] = [];
                        state.dataSource
                            .filter(
                                (item: any) =>
                                    item.sfkjzd === "1" || item.sfsjzd === "1"
                            )
                            .forEach((e: any) => {
                                if (e.sfkjzd === "1") {
                                    kjzd.push(e.zdmc);
                                }
                                if (e.sfsjzd === "1") {
                                    sjzd.push(e.zdmc);
                                }
                            });
                        const createObject = {
                            id: state.dataSource[0].sjjid,
                            kjzd: kjzd.join(","),
                            sjzd: sjzd.join(","),
                            dataSource,
                        };
                        emit("handleOk", createObject);
                        break;
                    case 1:
                    case 4:
                        const {
                            resetFields,
                            validate,
                            validateInfos,
                        } = useForm(
                            type.value === 1 ? form : addStore.addForm,
                            type.value === 1
                                ? rulesRef
                                : addStore.addForm.isMulti === 0
                                ? rulesRefAdd
                                : rulesRefAdd_tow
                        );
                        state.validateInfos = validateInfos;
                        state.resetFields = resetFields;
                        validate()
                            .then(() => {
                                emit(
                                    "handleOk",
                                    type.value === 1 ? form : addStore.addForm
                                );
                            })
                            .catch((err) => {
                                console.log("error", err);
                            });
                        break;
                    default:
                        break;
                }
            },
            handleCancel: () => {
                state.resetFields();
                emit("handleCancel");
            },
        });
        return {
            form,
            ryxx,
            ...toRefs(state),
            ...toRefs(props),
            ...toRefs(data),
            ...toRefs(addStore),
        };
    },
});
</script>
<style lang="less" scoped>
.table-tools {
    margin-bottom: 10px;
    display: flex;
    flex-direction: row-reverse;
    > button {
        margin-left: 4px;
    }
}
</style>
